<template>
  <div class="step-div">
    <a-steps :current="step.current">
      <a-step title="基础信息" />
      <a-step title="配置参数" />
      <a-step title="配置返回值" />
    </a-steps>
  </div>

  <a-form :label-col="{span: 6}" :wrapper-col="{span: 16}" v-show="step.current==0">
    <a-form-item label="接口名称" v-bind="validateInfos.name">
      <a-input v-model:value="modelRef.name" v-focus />
    </a-form-item>
    <a-form-item label="接口描述" v-bind="validateInfos.message">
      <a-input v-model:value="modelRef.message" />
    </a-form-item>
    <a-form-item label="接口地址" v-bind="validateInfos.uri">
      <a-input v-model:value="modelRef.uri" />
    </a-form-item>
    <a-form-item label="请求方式" v-bind="validateInfos.methodType">
      <a-select v-model:value="modelRef.methodType" :field-names="{ label: 'name', value: 'code', options: 'children' }" :options="methodTypeData"></a-select>
    </a-form-item>
    <a-form-item label="请求数据类型" v-bind="validateInfos.methodContentType">
      <a-select v-model:value="modelRef.methodContentType" :field-names="{ label: 'name', value: 'code', options: 'children' }" :options="methodContentTypeData"></a-select>
    </a-form-item>
    <a-form-item label="响应数据类型" v-bind="validateInfos.methodDataType">
      <a-select v-model:value="modelRef.methodDataType" :field-names="{ label: 'name', value: 'code', options: 'children' }" :options="methodDataTypeData"></a-select>
    </a-form-item>

    <a-form-item :wrapper-col="{ span: 14, offset: 6 }">
      <a-space>
        <a-button @click="resetFields">重置</a-button>
        <a-button type="primary" @click.prevent="onSubmitInfo">下一步</a-button>
      </a-space>
    </a-form-item>
  </a-form>

  <a-form :label-col="{span: 6}" :wrapper-col="{span: 16}" v-show="step.current==1" ref="formParamsRef" :model="modelParamsRef">
    <a-form-item :wrapper-col="{ span: 24 }">
      <a-space v-for="(param, index) in modelParamsRef.params" style="display: flex; margin-bottom: 8px" align="baseline">
        <a-form-item label="参数名称" :name="['params', index, 'name']" :rules="{required: true,message: '参数名称必填项'}">
          <a-input v-model:value="param.name" />
        </a-form-item>
        <a-form-item label="参数描述" :name="['params', index, 'message']" :rules="{required: true,message: '参数描述必填项'}">
          <a-input v-model:value="param.message" />
        </a-form-item>
        <a-form-item label="参数类型" :name="['params', index, 'type']" :rules="{required: true,message: '参数类型必填项'}">
          <a-select v-model:value="param.type" :field-names="{ label: 'name', value: 'code', options: 'children' }" :options="typeData" style="minWidth: 100px"></a-select>
        </a-form-item>
        <a-form-item label="是否必填">
          <a-switch v-model:checked="param.required" checked-children="是" un-checked-children="否" />
        </a-form-item>
        <a-form-item label="默认值">
          <a-input v-model:value="param.default" v-if="param.type=='String'"/>
          <a-input-number v-model:value="param.default" v-if="param.type=='Number'"/>
          <a-switch v-model:checked="param.default" checked-children="true" un-checked-children="false" v-if="param.type=='Boolean'"/>
        </a-form-item>
        <minus-circle-outlined @click="removeParams(index)"/>
      </a-space>

      <a-form-item>
        <a-button type="dashed" block @click="addParams">
          <PlusOutlined /> 添加参数
        </a-button>
      </a-form-item>
      <a-space>
        <a-button @click.prevent="preStep">上一步</a-button>
        <a-button type="primary" html-type="submit" @click="onSubmitParams">下一步</a-button>
      </a-space>
    </a-form-item>
  </a-form>

  <a-form :label-col="{span: 6}" :wrapper-col="{span: 16}" v-show="step.current==2" ref="formResultsRef" :model="modelResultsRef">
    <a-form-item :wrapper-col="{ span: 24 }">
      <a-space v-for="(result, index) in modelResultsRef.results" style="display: flex; margin-bottom: 8px" align="baseline">
        <a-form-item label="返回字段名" :name="['results', index, 'name']" :rules="{required: true,message: '返回字段名必填项'}">
          <a-input v-model:value="result.name" />
        </a-form-item>
        <a-form-item label="返回字段描述" :name="['results', index, 'message']" :rules="{required: true,message: '返回字段描述必填项'}">
          <a-input v-model:value="result.message" />
        </a-form-item>
        <a-form-item label="返回字段类型" :name="['results', index, 'type']" :rules="{required: true,message: '返回字段类型必填项'}">
          <a-select v-model:value="result.type" :field-names="{ label: 'name', value: 'code', options: 'children' }" :options="typeData" style="minWidth: 100px"></a-select>
        </a-form-item>
        <minus-circle-outlined @click="removeResults(index)" />
      </a-space>

      <a-form-item>
        <a-button type="dashed" block @click="addResults">
          <PlusOutlined /> 添加参数
        </a-button>
      </a-form-item>
      <a-space>
        <a-button @click.prevent="preStep">上一步</a-button>
        <a-button type="primary" html-type="submit" @click="onSubmitResults">保存</a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>
<script>
import { insert, update } from "@/api/platform/plInterfaceApi";
import { defineComponent, reactive, toRaw, ref } from "vue";
import { Form, message } from "ant-design-vue";
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons-vue";
const useForm = Form.useForm;
export default defineComponent({
  props: {
    type: String,
    row: Object
  },
  setup(props, context) {
    const { type, row } = props;
    const modelRef = reactive({
      name: row?.name,
      message: row?.message,
      uri: row?.uri,
      methodType: row?.methodType || "GET",
      methodContentType: row?.methodContentType || "none",
      methodDataType: row?.methodDataType || "application/json"
    });

    const step = reactive({
      current: 0
    });

    // 下一步
    const nextStep = () => {
      step.current++;
    };
    // 上一步
    const preStep = () => {
      step.current--;
    };

    const methodTypeData = reactive([
      {
        name: "GET请求",
        code: "GET"
      },
      {
        name: "POST请求",
        code: "POST"
      }
    ]);

    const methodContentTypeData = reactive([
      {
        name: "none",
        code: "none"
      },
      {
        name: "multipart/form-data",
        code: "multipart/form-data"
      },
      {
        name: "application/x-www-from-urlencoded",
        code: "application/x-www-from-urlencoded"
      },
      {
        name: "raw",
        code: "raw"
      }
    ]);

    const methodDataTypeData = reactive([
      {
        name: "application/json",
        code: "application/json"
      },
      {
        name: "application/text",
        code: "application/text"
      },
      {
        name: "application/html",
        code: "application/html"
      },
      {
        name: "application/octet-stream",
        code: "application/octet-stream"
      },
      {
        name: "application/x-protobuf",
        code: "application/x-protobuf"
      }
    ]);

    const typeData = reactive([
      {
        name: "String",
        code: "String"
      },
      {
        name: "Number",
        code: "Number"
      },
      {
        name: "Boolean",
        code: "Boolean"
      }
    ]);
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: "接口名称必填项"
        }
      ],
      message: [
        {
          required: true,
          message: "接口描述必填项"
        }
      ],
      uri: [
        {
          required: true,
          message: "接口地址必填项"
        }
      ],
      methodType: [
        {
          required: true,
          message: "请求方式必填项"
        }
      ],
      methodContentType: [
        {
          required: true,
          message: "请求数据类型必填项"
        }
      ],
      methodDataType: [
        {
          required: true,
          message: "响应数据类型必填项"
        }
      ]
    });

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );
    const onSubmitInfo = () => {
      validate()
        .then(() => {
          nextStep();
        })
        .catch(err => {
          console.log("error", err);
        });
    };

    const formParamsRef = ref();
    const modelParamsRef = reactive({
      params:
        row && row?.params
          ? JSON.parse(row?.params)
          : [
              {
                name: "",
                type: "String",
                message: "",
                required: false,
                default: ""
              }
            ]
    });
    const onSubmitParams = () => {
      formParamsRef.value
        .validate()
        .then(() => {
          nextStep();
        })
        .catch(error => {
          console.log("error", error);
        });
    };

    // 移除参数
    const removeParams = index => {
      modelParamsRef.params.splice(index, 1);
    };

    // 添加参数
    const addParams = () => {
      modelParamsRef.params.push({
        name: "",
        type: "String",
        message: "",
        required: false,
        default: ""
      });
    };

    const formResultsRef = ref();
    const modelResultsRef = reactive({
      results:
        row && row?.results
          ? JSON.parse(row?.results)
          : [
              {
                name: "",
                type: "String",
                message: ""
              }
            ]
    });
    const onSubmitResults = () => {
      formResultsRef.value
        .validate()
        .then(() => {
          if (type == "insert") {
            insertData();
          } else if (type == "update") {
            updateData();
          }
        })
        .catch(error => {
          console.log("error", error);
        });
    };

    // 移除参数
    const removeResults = index => {
      modelResultsRef.results.splice(index, 1);
    };

    // 添加参数
    const addResults = () => {
      modelResultsRef.results.push({
        name: "",
        type: "String",
        message: ""
      });
    };

    const insertData = () => {
      let form = toRaw(modelRef);
      let modelParams = toRaw(modelParamsRef);
      let modelResults = toRaw(modelResultsRef);

      form.params = JSON.stringify(modelParams.params);
      form.results = JSON.stringify(modelResults.results);

      insert(form).then(resd => {
        message.success("创建成功");
        context.emit("success", resd);
      });
    };

    const updateData = () => {
      let form = toRaw(modelRef);
      let modelParams = toRaw(modelParamsRef);
      let modelResults = toRaw(modelResultsRef);
      form.params = JSON.stringify(modelParams.params);
      form.results = JSON.stringify(modelResults.results);
      form.id = row.id;
      update(form).then(resd => {
        message.success("更新成功");
        context.emit("success", resd);
      });
    };

    return {
      formParamsRef,
      formResultsRef,
      validateInfos,
      resetFields,
      modelRef,
      modelParamsRef,
      modelResultsRef,
      removeParams,
      removeResults,
      addParams,
      addResults,
      step,
      onSubmitInfo,
      onSubmitParams,
      onSubmitResults,
      methodTypeData,
      methodContentTypeData,
      methodDataTypeData,
      typeData,
      preStep
    };
  },
  components: { MinusCircleOutlined, PlusOutlined }
});
</script>

<style scoped lang="scss">
.step-div {
  padding: 20px;
}
</style>